<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <!-- 添加分类 -->
      <el-button
        type="primary"
        size="mini"
        class="addCateBtn"
        @click="showAddCateDialog"
        >添加分类</el-button
      >

      <!-- 表格 -->
      <tree-table
        :data="cateList"
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
        show-index
        border
        :show-row-hover="false"
        index-text="#"
      >
        <!-- 是否有效 -->
        <template slot="isOk" slot-scope="scope">
          <i class="el-icon-success" v-if="!scope.row.cat_deleted"></i>
          <i class="el-icon-error" v-else></i>
        </template>

        <!-- 排序 -->
        <template slot="sort" slot-scope="scope">
          <el-tag v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag type="success" v-else-if="scope.row.cat_level === 1"
            >二级</el-tag
          >
          <el-tag type="warning" v-else>三级</el-tag>
        </template>

        <!-- 操作 -->
        <template slot="opt" slot-scope="scope">
          <!-- 编辑 -->
          <el-button
            type="primary"
            icon="el-icon-edit"
            @click="showEditCate(scope.row.cat_id)"
            size="mini"
          ></el-button>

          <!-- 删除 -->
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="removeCate(scope.row.cat_id)"
          ></el-button>
        </template>
      </tree-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 5, 10, 15]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加分类对话框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addCateDialogVisible"
      width="50%"
      @close="handleAddCateClose"
    >
      <el-form
        :model="addCateForm"
        :rules="addCateRules"
        ref="addCateRef"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>

        <el-form-item label="父级分类" prop="cat_pid">
          <el-cascader
            v-model="selectedKeys"
            :options="parentCateList"
            :props="carcaderProps"
            @change="parentCateChange"
            clearable
          ></el-cascader>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="addCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑分类对话框 -->
    <el-dialog
      title="编辑分类"
      :visible.sync="editCateDialogVisible"
      width="50%"
      @close="handleEditCateClose"
    >
      <el-form
        :model="editCateForm"
        :rules="editCateRules"
        ref="editCateRef"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="editCateForm.cat_name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCate">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  created() {
    this.getCateList()
  },
  data() {
    const catNameReg = [
      { required: true, message: '请输入分类名称', trigger: 'blur' }
    ]
    return {
      // 商品分类的数据列表
      cateList: [],
      // 查询条件
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      // 总条数
      total: 0,
      // 表格列
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name'
        },
        {
          label: '是否有效',
          prop: 'cat_deleted',
          width: '80px',
          type: 'template',
          template: 'isOk'
        },
        {
          label: '排序',
          width: '80px',
          prop: 'cat_level',
          type: 'template',
          template: 'sort'
        },
        {
          label: '操作',
          prop: 'likes',
          width: '125px',
          type: 'template',
          template: 'opt'
        }
      ],
      // 添加分类对话框显示状态
      addCateDialogVisible: false,
      // 添加分类 - 校验规则
      addCateRules: {
        cat_name: catNameReg
      },
      // 添加分类的表单数据对象
      addCateForm: {
        // 分类父 ID
        cat_pid: 0,
        // 分类名称
        cat_name: '',
        // 分类层级
        cat_level: 0
      },
      // 父级分类列表
      parentCateList: [],
      // 选中父级分类的id数组
      selectedKeys: [],
      // 指定级联选择器的配置对象
      carcaderProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        checkStrictly: true
      },
      // 编辑分类对话框显示状态
      editCateDialogVisible: false,
      editCateRules: {
        cat_name: catNameReg
      },
      editCateForm: {
        cat_id: 0,
        cat_name: ''
      }
    }
  },
  methods: {
    // 获取商品分类数据
    async getCateList() {
      const { data: res } = await this.$http.get('categories', {
        params: this.queryInfo
      })

      if (res.meta.status !== 200) {
        return this.message.error(res.meta.msg)
      } else {
        this.cateList = res.data.result
        this.total = res.data.total
      }
    },

    // 监听每页条数事件
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getCateList()
    },

    // 监听当前页码事件
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getCateList()
    },

    // 监听添加分类对话框关闭
    handleAddCateClose() {
      this.$refs.addCateRef.resetFields()
      this.selectedKeys = []
      this.addCateForm.cat_pid = 0
      this.addCateForm.cat_level = 0
    },

    // 显示添加分类对话框
    showAddCateDialog() {
      this.getParantCateList()
      this.addCateDialogVisible = true
    },

    // 获取父级分类的数据列表
    async getParantCateList() {
      const { data: res } = await this.$http.get('categories', {
        params: {
          type: 2
        }
      })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      } else {
        this.parentCateList = res.data
      }
    },

    // 监听选择项变化
    parentCateChange() {
      if (this.selectedKeys.length > 0) {
        this.addCateForm.cat_pid = this.selectedKeys[
          this.selectedKeys.length - 1
        ]
        this.addCateForm.cat_level = this.selectedKeys.length
      } else {
        this.addCateForm.cat_pid = 0
        this.addCateForm.cat_level = 0
      }
    },

    // 添加分类
    addCate() {
      this.$refs.addCateRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.error('请完善表单数据')
        } else {
          const { data: res } = await this.$http.post(
            'categories',
            this.addCateForm
          )
          if (res.meta.status !== 201) {
            return this.$message.error(res.meta.msg)
          } else {
            this.$message.success(res.meta.msg)
            this.getCateList()
            this.addCateDialogVisible = false
          }
        }
      })
    },

    // 显示编辑分类对话框
    async showEditCate(id) {
      const { data: res } = await this.$http.get(`categories/${id}`)
      if (res.meta.status !== 200) {
        return this.$messgae.error(res.meta.msg)
      } else {
        this.editCateForm = res.data
        this.editCateDialogVisible = true
      }
    },

    // 监听编辑对话框关闭
    handleEditCateClose() {
      this.$refs.editCateRef.resetFields()
    },

    // 编辑分类
    async editCate() {
      console.log(this.editCateForm)
      const { data: res } = await this.$http.put(
        `categories/${this.editCateForm.cat_id}`,
        this.editCateForm
      )
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      } else {
        this.$message.success(res.meta.msg)
        this.getCateList()
        this.editCateDialogVisible = false
      }
    },

    // 删除分类
    async removeCate(id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该分类, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)

      if (confirmResult !== 'confirm') {
        return this.$message('用户取消了删除操作')
      } else {
        const { data: res } = await this.$http.delete(`categories/${id}`)
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        } else {
          this.getCateList()
          this.$message.success(res.meta.msg)
        }
      }
    }
  }
}
</script>
<style lang="less" scoped>
.el-icon-success {
  color: green;
  font-size: 18px;
}
.el-icon-error {
  color: red;
  font-size: 18px;
}
.addCateBtn {
  margin-bottom: 15px;
}
.el-cascader {
  width: 100%;
}
</style>
